/*************************************************************************
 * configurations
 *************************************************************************/
// time in milliseconds to be able to see two turned memory images.
var returnTimeout = 1500;
// this image is displayed if the field has no memory card any more.
var spaceImage = "gfx/space.gif";
var greyImage = "gfx/grey_pixel.jpg";


/*************************************************************************
 *
 *************************************************************************/
var cardsMap = new Array();
var imageSet;
var cardCount;
var oktoclick = false;
var solvedPairs = 0;
var turnedCardPairs = new Array(0, 0);
var numberOfCardsTurned = 0;
var numberOfTries = 0;

var allowQuickContinuing = false;
function initMemory()
{
   imageSet = getTheImageSet();
   preloadImages(imageSet);
   cardCount = imageSet.cardImages.length * 2;
   createCardMap();
   scramble();
   renderMemory();
   oktoclick = true;
   solvedPairs = 0;
   numberOfTries = 0;
   showNumberOfTries();
}

/*
* renders the html to show the memory cards.
*/
function renderMemory()
{
   // render the memory field
   var memoryField = document.getElementById("memoryMap")
   var memoryHtml = '<table cellpadding="0" cellspacing="5" border="0">';
   var cardIndex = 0;
   var cardsOnRowCount = determineCardsOnRow();
   while (cardIndex < cardCount)
   {
      memoryHtml += '<tr>';
      for (var column = 0; column < cardsOnRowCount && cardIndex < cardCount; column++)
      {
         memoryHtml += '<td className="memoryField" align="center" valign="middle" width="40" height="40">';
         memoryHtml += '<a href="javascript:showImage(' + cardIndex + ')" >';
         memoryHtml += '<img src="' + imageSet.cardBackImage + '" id="card' + cardIndex + '" height="' + imageSet.cardHeight + '" width="' + imageSet.cardWidth + '" border="0"/>';
         memoryHtml += '</a></td>';
         cardIndex++;
      }
      memoryHtml += '</tr>';
   }
   memoryHtml += '</table>';
   memoryField.innerHTML = memoryHtml;

   // render the status field
   var statusField = document.getElementById("statusField");
   var statusHtml = '<table cellpadding="0" cellspacing="10" border="0">';

   var imageIndex = 0
   while (imageIndex < imageSet.cardImages.length)
   {
      statusHtml += '<tr><td align="center" valign="middle" width="40" height="40">';
      statusHtml += '<img src="' + greyImage + '" id="solvedCard' + imageIndex + '" height="' + (imageSet.cardHeight / 2) + '" width="' + (imageSet.cardWidth / 2) + '" border="0">';
      statusHtml += '</td>';
      imageIndex ++;
      if (imageIndex < imageSet.cardImages.length)
      {
         statusHtml += '<td align="center" valign="middle" width="40" height="40">';
         statusHtml += '<img src="' + greyImage + '" id="solvedCard' + imageIndex + '" height="' + (imageSet.cardHeight / 2) + '" width="' + (imageSet.cardWidth / 2) + '" border="0">';
         statusHtml += '</td></tr>';
         imageIndex ++;
      }
   }
   statusHtml += '</table>';
   statusField.innerHTML = statusHtml;
}

/*
* shows the images at the given cardIndex. If it is allowed.
*/
function showImage(cardIndex)
{
   if (allowQuickContinuing)
   {
      returnCards();
   }
   if (numberOfCardsTurned <= 1)
   {
      var card = document.getElementById("card" + cardIndex);
      if (canTurnCard(card))
      {
         card.src = cardsMap[cardIndex];
         if (numberOfCardsTurned == 0)
         {
            numberOfCardsTurned++;
            turnedCardPairs[0] = card;
            oktoclick = true;
         }
         else if (numberOfCardsTurned == 1)
         {
            numberOfTries++;
            showNumberOfTries();
            turnedCardPairs[1] = card;
            numberOfCardsTurned++;
            //setTimeout('returnCards()', returnTimeout);
            checkCards();
         }
      }
   }
}

function showNumberOfTries()
{
   var numberOfTriesElement = document.getElementById('numberOfTries');
   numberOfTriesElement.innerHTML = "aantal pogingen:" + numberOfTries;
}
// check if clicked on already turned (hidden) card.
function canTurnCard(card)
{
   var canTurn = false;
   var imageOfCard = card.src.substring(card.src.lastIndexOf("/") + 1);
   var cardBackImage = imageSet.cardBackImage;
   var imageOfCardBackImage = cardBackImage.substring(cardBackImage.lastIndexOf("/") + 1);
   if (imageOfCard == imageOfCardBackImage)
   {
      canTurn = true;
   }
   return canTurn;
}
/*
* Shows all memory cards.
*/
function solveMemory()
{
   for (var cardIndex = 0; cardIndex < cardCount; cardIndex++)
   {
      var card = document.getElementById("card" + cardIndex);
      card.src = cardsMap[cardIndex];
   }
}


/*
* check the turned cards. If two cards are turned and there images
* are the same they stay visable.
*/
function checkCards()
{
   var turnedCard1 = turnedCardPairs[0];
   var turnedCard2 = turnedCardPairs[1];
   if (turnedCard1.src == turnedCard2.src)
   {
      setTimeout('handleSolvedPair()', returnTimeout);

   }
   else
   {
      //showMessage(messageTakeALook);
      setTimeout('returnCards()', returnTimeout);
   }
}

function handleSolvedPair()
{
   if (numberOfCardsTurned == 2)
   {
      numberOfCardsTurned = 0;
      var turnedCard1 = turnedCardPairs[0];
      var turnedCard2 = turnedCardPairs[1];
      var solvedCard = document.getElementById("solvedCard" + solvedPairs);
      solvedCard.src = turnedCard1.src;
      turnedCard1.src = spaceImage;
      turnedCard2.src = spaceImage;
      if (solvedPairs == imageSet.cardImages.length)
      {
         //showMessage(messageSolved);
      }
      solvedPairs ++;
   }

}
/*
* returns the cards if two cards are turned and there images aren't the same.
*/
function returnCards()
{
   if (numberOfCardsTurned == 2)
   {
      numberOfCardsTurned = 0;
      var turnedCard1 = turnedCardPairs[0];
      var turnedCard2 = turnedCardPairs[1];
      turnedCard1.src = imageSet.cardBackImage;
      turnedCard2.src = imageSet.cardBackImage;
      //showMessage(messageGone);
   }
}

/*
* selected the imageSet to use for the memory game.
*/
function getImageSet(imageSetName)
{
   for (var imageSetIndex = 0; imageSetIndex < allImagesSet.length; imageSetIndex++)
   {
      var tempImageSet = allImagesSet[imageSetIndex];
      if (tempImageSet.name == imageSetName)
      {
         return tempImageSet;
      }
   }
   return new imageSet();
}


function preloadImages(imageSet)
{
   if (document.images)
   {
      var preload_image = new Image();
      preload_image.src = imageSet.cardBackImage;

      for (var imageIndex = 0; imageIndex < imageSet.cardImages.length; imageIndex++)
      {
         preload_image.src = imageSet.cardImages[imageIndex];
      }
   }
}

var messageStart = 0;
var messageTakeALook = 1;
var messageGone = 2;
var messageSolved = 3;
/*
* depending on the messageKey (defined above this function)
* shows a message on the html field.
*/
function showMessage(messageKey)
{
   if (messageKey == messageStart)
   {
      document.getElementById("messageBoxStart").style.display = "block";
      document.getElementById("messageBoxTakeALook").style.display = "none";
      document.getElementById("messageBoxGone").style.display = "none";
      document.getElementById("messageBoxSolved").style.display = "none";
   }
   if (messageKey == messageTakeALook)
   {
      document.getElementById("messageBoxStart").style.display = "none";
      document.getElementById("messageBoxTakeALook").style.display = "block";
      document.getElementById("messageBoxGone").style.display = "none";
      document.getElementById("messageBoxSolved").style.display = "none";
   }
   else if (messageKey == messageGone)
   {
      document.getElementById("messageBoxStart").style.display = "none";
      document.getElementById("messageBoxTakeALook").style.display = "none";
      document.getElementById("messageBoxGone").style.display = "block";
      document.getElementById("messageBoxSolved").style.display = "none";
   }
   else if (messageKey == messageSolved)
   {
      document.getElementById("messageBoxStart").style.display = "none";
      document.getElementById("messageBoxTakeALook").style.display = "none";
      document.getElementById("messageBoxGone").style.display = "none";
      document.getElementById("messageBoxSolved").style.display = "block";
   }
   else
   {
      document.getElementById("messageBoxStart").style.display = "none";
      document.getElementById("messageBoxTakeALook").style.display = "none";
      document.getElementById("messageBoxGone").style.display = "none";
      document.getElementById("messageBoxSolved").style.display = "none";
   }
}

/*
* fills the cardsMap with the selected images.
*/
function createCardMap()
{
   for (var cardIndex = 0; cardIndex < cardCount; cardIndex++)
   {
      var imageIndex = Math.round((cardIndex - 1) / 2);
      cardsMap[cardIndex] = imageSet.cardImages[imageIndex]
   }
}

/*
* scrambles the cardsMap.
*/
var temparray = new Array();
function scramble()
{
   for (var z = 0; z < 5; z++)
   {
      for (var cardIndex = 0; cardIndex < cardCount; cardIndex++)
      {
         temparray[0] = Math.floor(Math.random() * cardCount);
         temparray[1] = cardsMap[temparray[0]];
         temparray[2] = cardsMap[cardIndex];
         cardsMap[cardIndex] = temparray[1];
         cardsMap[temparray[0]] = temparray[2];
      }
   }
}

/*
* calculates the number of cards to be printed one single row.
*/
function determineCardsOnRow()
{
   //var usableWidth = screen.width - imageSet.cardWidth - (screen.width * 0.02);
   var usableWidth = screen.width - 2 * imageSet.cardWidth;
   var maxCardsOnRow = Math.floor(usableWidth / imageSet.cardWidth);
   var usableHeight = screen.height - screen.height * 0.3
   //var maxCardsOnColumn = Math.floor(usableHeight / imageSet.cardHeight);
   var calculatedCardsOnRow = Math.round(Math.sqrt((cardCount * usableWidth) / usableHeight));

   if (calculatedCardsOnRow > maxCardsOnRow)
   {
      calculatedCardsOnRow = maxCardsOnRow;
   }
   return calculatedCardsOnRow;
}
